package com.financing.service.invest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.financing.enums.invest.BidStatus;
import com.financing.model.invest.Bid;
import com.financing.model.invest.BidDetail;
import com.financing.model.invest.BidVirtualLog;
import com.financing.service.BaseService;
import com.financing.service.system.LoggerService;
import com.financing.util.Money;
import com.financing.util.Str;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

public class BidVirtualLogService extends BaseService<BidDetail>{
	private LoggerService log = new LoggerService();
	
	/**
	 * 根据标的ID查找
	 * @return List<BidVirtualLog>
	 */
	public List<BidVirtualLog> findByBid(int bidId) {
		return BidVirtualLog.me.find("select * from bid_virtual_log where bid_id=?", bidId);
	}
	
	/**
	 * 分页信息
	 */
	public Page<BidVirtualLog> list(int page, int size, Map<String, String> map) {
		return BidVirtualLog.me.paginate(page, size, buildSql("bid_virtual_log",Arrays.asList("create_time"),map));
	}
	
	/**
	 * 虚增份数
	 * @param u
	 * @param bidId
	 * @param unit
	 * @return Ret
	 * @throws Exception 
	 */
	public Ret plus(int bidId, int unit, int userId) throws Exception {

		if(unit>0){
			Date now = new Date();
			Bid b = Bid.me.findById(bidId);
			if(b.isExperi() && unit % 10000 != 0) {
				return Ret.fail("msg","体验标修改数量必须为10000的倍数！");
			}
			if(b!=null && Str.eq(BidStatus.TRADING, b.getStatus())){
				
				if(b.getApplyUnit()+b.getVirtualUnit()+unit<=b.getUnit()) {

					BidVirtualLog bvl = new BidVirtualLog();
					bvl.setUserId(userId);
					bvl.setBidId(b.getId());
					bvl.setMobile(Str.getTel());
					bvl.setAmount(Money.mul(b.getUnitAmount(), unit));
					bvl.setCreateTime(now);
					bvl.save();
					
					// 数量增加
					b.setJoinNum(new TradeService().userCount(b)).setVirtualUnit(b.getVirtualUnit()+unit);
					
					// 判断是否满标	
            		if(b.getApplyUnit() + b.getVirtualUnit() >=b.getUnit()){
            			b.setStatus(BidStatus.FULL);
            		}
					
            		b.update();
            		
					log.build("标的数量虚增成功", "标的ID："+b.getId()+" 名称："+b.getName()+" 份数："+unit, userId, "backend");
					
					return Ret.ok();
				} else {
					return Ret.fail("msg","修改数量不可大于最大份数！");
				}
			} else {
				return Ret.fail("msg","标的状态不正确！");
			}
		} else {
			return Ret.fail("msg","虚增数量至少大于0！");
		}
	}
}
